﻿// -----------------------------------------------------------------------
//  <copyright file="DaprPlusHub.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://ifs.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-09-28 00:09</last-date>
// -----------------------------------------------------------------------

using Microsoft.AspNetCore.SignalR;


namespace DaprPlus.AspNetCore.SignalR;

public abstract class DaprPlusHub(IServiceProvider provider) : Hub
{
    private readonly IConnectionUserCache _cache = provider.GetRequiredService<IConnectionUserCache>();
    private readonly ILogger<DaprPlusHub> _logger = provider.GetLogger<DaprPlusHub>();

    /// <summary>
    /// 当与集线器建立新的连接时会被调用。
    /// </summary>
    public override async Task OnConnectedAsync()
    {
        await InternalHubHelper.HandleConnectedAsync(_cache, Context, _logger);
        await base.OnConnectedAsync();
    }

    /// <summary>与集线器的连接被终止时调用。</summary>
    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        await InternalHubHelper.HandleDisconnectedAsync(_cache, Context, _logger, exception);
        await base.OnDisconnectedAsync(exception);
    }

    /// <summary>
    /// 加入组
    /// </summary>
    /// <param name="groupNames">组名</param>
    /// <returns></returns>
    public virtual Task AddToGroup(params string[] groupNames)
    {
        return InternalHubHelper.HandleAddToGroup(Groups, Context, _logger, groupNames);
    }

    public virtual Task RemoveFromGroup(params string[] groupNames)
    {
        return InternalHubHelper.HandleRemoveFromGroup(Groups, Context, _logger, groupNames);
    }
}

public abstract class DaprPlusHub<T>(IServiceProvider provider)
    : Hub<T> where T : class
{

    private readonly IConnectionUserCache _cache = provider.GetRequiredService<IConnectionUserCache>();
    private readonly ILogger<DaprPlusHub> _logger = provider.GetLogger<DaprPlusHub>();

    /// <summary>
    /// 当与集线器建立新的连接时会被调用。
    /// </summary>
    public override async Task OnConnectedAsync()
    {
        await InternalHubHelper.HandleConnectedAsync(_cache, Context, _logger);
        await base.OnConnectedAsync();
    }

    /// <summary>与集线器的连接被终止时调用。</summary>
    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        await InternalHubHelper.HandleDisconnectedAsync(_cache, Context, _logger, exception);
        await base.OnDisconnectedAsync(exception);
    }

    /// <summary>
    /// 加入组
    /// </summary>
    /// <param name="groupNames">组名</param>
    /// <returns></returns>
    public virtual Task AddToGroup(params string[] groupNames)
    {
        return InternalHubHelper.HandleAddToGroup(Groups, Context, _logger, groupNames);
    }

    public virtual Task RemoveFromGroup(params string[] groupNames)
    {
        return InternalHubHelper.HandleRemoveFromGroup(Groups, Context, _logger, groupNames);
    }
}